package com.farsunset.cim.client.android;

import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.UUID;


import com.farsunset.cim.nio.constant.CIMConstant;
import com.farsunset.cim.nio.mutual.SentBody;
import com.farsunset.cim.nio.util.MD5FileUtil;

/**
 * IM 功能接口
 * 
 */
public class CIMPushManager {

	static String ACTION_CONNECTION_KEEPALIVE = "ACTION_CONNECTION_KEEPALIVE";

	static String ACTION_CONNECTION = "ACTION_CONNECTION";

	static String ACTION_CONNECTION_STATUS = "ACTION_CONNECTION_STATUS";

	static String ACTION_SENDREQUEST = "ACTION_SENDREQUEST";

	static String ACTION_DISCONNECTION = "ACTION_DISSENDREQUEST";

	static String ACTION_DESTORY = "ACTION_DESTORY";

	static String SERVICE_ACTION = "SERVICE_ACTION";

	static String KEY_SEND_BODY = "KEY_SEND_BODY";

	static String KEY_CIM_CONNECTION_STATUS = "KEY_CIM_CONNECTION_STATUS";

	
	//文件相关
	private static int byteRead;
	private volatile static long start = 0;
	public static RandomAccessFile randomAccessFile;
	//读取大小
	private final static int minReadBufferSize = 1024 * 20;
	
	
	/**
	 * 初始化,连接服务端，在程序启动页或者 在Application里调用
	 * 
	 * @param context
	 * @param ip
	 * @param port
	 */
	public static void init(Context context, String ip, int port) {

		CIMDataConfig.putBoolean(context, CIMDataConfig.KEY_CIM_DESTORYED,
				false);
		CIMDataConfig.putBoolean(context, CIMDataConfig.KEY_MANUAL_STOP, false);

		Intent serviceIntent = new Intent(context, CIMPushService.class);
		serviceIntent.putExtra(CIMDataConfig.KEY_CIM_SERVIER_HOST, ip);
		serviceIntent.putExtra(CIMDataConfig.KEY_CIM_SERVIER_PORT, port);
		serviceIntent.putExtra(SERVICE_ACTION, ACTION_CONNECTION);
		context.startService(serviceIntent);
		CIMDataConfig
				.putString(context, CIMDataConfig.KEY_CIM_SERVIER_HOST, ip);
		CIMDataConfig.putInt(context, CIMDataConfig.KEY_CIM_SERVIER_PORT, port);
	}

	protected static void init(Context context) {

		boolean isManualStop = CIMDataConfig.getBoolean(context,
				CIMDataConfig.KEY_MANUAL_STOP);
		boolean isManualDestory = CIMDataConfig.getBoolean(context,
				CIMDataConfig.KEY_CIM_DESTORYED);

		if (isManualStop || isManualDestory) {
			return;
		}

		String host = CIMDataConfig.getString(context,
				CIMDataConfig.KEY_CIM_SERVIER_HOST);
		int port = CIMDataConfig.getInt(context,
				CIMDataConfig.KEY_CIM_SERVIER_PORT);

		init(context, host, port);

	}

	/**
	 * 设置一个账号登录到服务端
	 * 
	 * @param account
	 *            用户唯一ID
	 */
	public static void setAccount(Context context, String account) {

		boolean isManualDestory = CIMDataConfig.getBoolean(context,
				CIMDataConfig.KEY_CIM_DESTORYED);
		if (isManualDestory || account == null || account.trim().length() == 0) {
			return;
		}

		CIMDataConfig.putBoolean(context, CIMDataConfig.KEY_MANUAL_STOP, false);
		CIMDataConfig.putString(context, CIMDataConfig.KEY_ACCOUNT, account);

		String imei = ((TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
		imei += context.getPackageName();
		SentBody sent = new SentBody();
		sent.setKey(CIMConstant.RequestKey.CLIENT_BIND);
		sent.put("account", account);
		sent.put("deviceId", UUID.nameUUIDFromBytes(imei.getBytes()).toString()
				.replaceAll("-", ""));
		sent.put("channel", "android");
		sent.put("device", android.os.Build.MODEL);

		sendRequest(context, sent);

	}
	
	/**
	 * 设置一个文件
	 * @Title: setFile 
	 * @throws
	 */
	public static void setFile(Context context,String fileName,String account){
		
		System.out.println("调用到了文件发送方法...");
		
		boolean isManualDestory = CIMDataConfig.getBoolean(context,
				CIMDataConfig.KEY_CIM_DESTORYED);
		if (isManualDestory || account == null || account.trim().length() == 0) {
			return;
		}

		CIMDataConfig.putBoolean(context, CIMDataConfig.KEY_MANUAL_STOP, false);
		CIMDataConfig.putString(context, CIMDataConfig.KEY_ACCOUNT, account);

		String imei = ((TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
		imei += context.getPackageName();
		
		
		SentBody sent = new SentBody();
		//设置为传输文件类型
		sent.setKey(CIMConstant.RequestKey.CLIENT_TRANS_FILE);
		sent.put("account", account);
		sent.put("deviceId", UUID.nameUUIDFromBytes(imei.getBytes()).toString()
				.replaceAll("-", ""));
		sent.put("channel", "android");
		sent.put("device", android.os.Build.MODEL);
		
		//设置文件属性
		if (fileName != null && !fileName.equals("")) {
			File file = new File(fileName);
			
			//已只读的方式读取此文件
			int a = 0;
			try {
				randomAccessFile = new RandomAccessFile(file,
						"r");
				randomAccessFile.seek(start);
				
				//a=文件总长度-开始位置 = 剩余量
				a = (int) (randomAccessFile.length() - start);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			
			//赋值为最小读取长度
			int sendLength = minReadBufferSize;
			//当剩余量小于最小长度
			if (a < minReadBufferSize) {
				sendLength = a;
			}
			byte[] bytes = new byte[sendLength];
			
			sent.put("fileName", file.getName());
			
			String bytesStr = "";
			try {
				if ((byteRead = randomAccessFile.read(bytes)) != -1
						&& (randomAccessFile.length() - start) > 0) {
					bytesStr = com.farsunset.cim.nio.util.Base64Coder.encode(bytes);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			sent.put("bytes", bytesStr);
			sent.put("startPos", "0");
			sent.put("endPos", byteRead+"");
			
			String fileMd5 = "";
			try {
				fileMd5 = MD5FileUtil.getFileMD5String(file);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			
			sent.put("fileMd5", fileMd5);
			sent.put("fileType", fileName.substring(fileName.lastIndexOf("."),
					fileName.length()));
			sent.put("fileSize", file.length()+"");
			
			CIMDataConfig.fileMap.put(fileMd5, file);
		}
		System.out.println("文件相关属性已经设置完成...");
		
		System.out.println("客户端要发送的文件数据为:"+sent);
		//发送
		sendRequest(context, sent);
	}
	

	/**
	 * 客户端主动发送消息
	 */
	public static void setMsg(Context context,String content,String account){
		
		boolean isManualDestory = CIMDataConfig.getBoolean(context,
				CIMDataConfig.KEY_CIM_DESTORYED);
		if (isManualDestory || account == null || account.trim().length() == 0) {
			return;
		}

		CIMDataConfig.putBoolean(context, CIMDataConfig.KEY_MANUAL_STOP, false);
		CIMDataConfig.putString(context, CIMDataConfig.KEY_ACCOUNT, account);

		String imei = ((TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
		imei += context.getPackageName();
		
		
		SentBody sent = new SentBody();
		//设置为传输文件类型 可以不需要  
		sent.setKey(CIMConstant.RequestKey.CLIENT_SEND_MSG);
		sent.put("account", account);
		sent.put("deviceId", UUID.nameUUIDFromBytes(imei.getBytes()).toString()
				.replaceAll("-", ""));
		sent.put("channel", "android");
		sent.put("device", android.os.Build.MODEL);
		
		//设置要发送的内容
		sent.put("content", content);
		System.out.println("客户端主动发送消息的内容为:"+sent.toString());
		
		//发送
		sendRequest(context, sent);
	}
	

	protected static void setAccount(Context context) {

		String account = CIMDataConfig.getString(context,
				CIMDataConfig.KEY_ACCOUNT);
		setAccount(context, account);
	}

	/**
	 * 发送一个IM请求
	 * 
	 * @param context
	 * @body
	 */
	public static void sendRequest(Context context, SentBody body) {

		boolean isManualStop = CIMDataConfig.getBoolean(context,
				CIMDataConfig.KEY_MANUAL_STOP);
		boolean isManualDestory = CIMDataConfig.getBoolean(context,
				CIMDataConfig.KEY_CIM_DESTORYED);

		if (isManualStop || isManualDestory) {
			return;
		}

		Intent serviceIntent = new Intent(context, CIMPushService.class);
		serviceIntent.putExtra(KEY_SEND_BODY, body);
		serviceIntent.putExtra(SERVICE_ACTION, ACTION_SENDREQUEST);
		context.startService(serviceIntent);

	}

	/**
	 * 停止接受推送，将会退出当前账号登录，端口与服务端的连接
	 * 
	 * @param context
	 */
	public static void stop(Context context) {

		boolean isManualDestory = CIMDataConfig.getBoolean(context,
				CIMDataConfig.KEY_CIM_DESTORYED);
		if (isManualDestory) {
			return;
		}

		CIMDataConfig.putBoolean(context, CIMDataConfig.KEY_MANUAL_STOP, true);

		Intent serviceIntent = new Intent(context, CIMPushService.class);
		serviceIntent.putExtra(SERVICE_ACTION, ACTION_DISCONNECTION);
		context.startService(serviceIntent);

	}

	/**
	 * 完全销毁IM，一般用于完全退出程序，调用resume将不能恢复
	 * 
	 * @param context
	 */
	public static void destory(Context context) {

		CIMDataConfig
				.putBoolean(context, CIMDataConfig.KEY_CIM_DESTORYED, true);
		CIMDataConfig.putString(context, CIMDataConfig.KEY_ACCOUNT, null);

		Intent serviceIntent = new Intent(context, CIMPushService.class);
		serviceIntent.putExtra(SERVICE_ACTION, ACTION_DESTORY);
		context.startService(serviceIntent);

	}

	/**
	 * 重新恢复接收推送，重新连接服务端，并登录当前账号
	 * 
	 * @param context
	 */
	public static void resume(Context context) {

		boolean isManualDestory = CIMDataConfig.getBoolean(context,
				CIMDataConfig.KEY_CIM_DESTORYED);
		if (isManualDestory) {
			return;
		}

		setAccount(context);
	}

	public void detectIsConnected(Context context) {
		Intent serviceIntent = new Intent(context, CIMPushService.class);
		serviceIntent.putExtra(SERVICE_ACTION, ACTION_CONNECTION_STATUS);
		context.startService(serviceIntent);
	}

}